package cn.gov.msa.service.impl;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import cn.gov.msa.dao.RuleMapper;
import cn.gov.msa.dao.RuleTimeMapper;
import cn.gov.msa.model.Rule;
import cn.gov.msa.model.RuleTime;
import cn.gov.msa.pagehelper.CustomPageHelper;
import cn.gov.msa.service.RuleService;

public class RuleServiceImpl implements RuleService{
	
	@Autowired
	private RuleMapper ruleMapper;
	
	@Autowired
	private RuleTimeMapper ruleTimeMapper;
	
	@Transactional
	@Override
	public List<Rule> selectData(int pageNum, int pageSize,Rule rule) {
		CustomPageHelper.startPage(pageNum, pageSize); // 核心分页代码  
		List<Rule> list= ruleMapper.selectData(rule);		
		return list;
	}

	@Transactional
	@Override
	public int insertRule(Rule rule) {
		// TODO Auto-generated method stub
		return ruleMapper.insertRule(rule);
	}

	@Transactional
	@Override
	public int deleteRule(String ruleId) {
		// TODO Auto-generated method stub
		int result = ruleTimeMapper.deleteByRuleId(ruleId);
	    result = ruleMapper.deleteRule(ruleId);
		return result;
	}

	@Transactional
	@Override
	public int updateRule(Rule rule,List<RuleTime> ruleTime) {
		// TODO Auto-generated method stub
		int result = 0;
		ruleTimeMapper.deleteByRuleId(rule.getRuleid());
		result = ruleMapper.updateRule(rule);
		for (RuleTime rtime : ruleTime) {
			rtime.setRuleid(rule.getRuleid());
			rtime.setRuleidtime(UUID.randomUUID().toString());
			ruleTimeMapper.insert(rtime);
		}
		return ruleMapper.updateRule(rule);
	}
	
	
	@Transactional
	public boolean saveData(Rule rule, List<RuleTime> ruleTime) throws Exception {
		boolean result = false;
		rule.setRuleid(UUID.randomUUID().toString());
		int irule = ruleMapper.insertRule(rule);
		
		for (RuleTime rtime : ruleTime) {
			rtime.setRuleid(rule.getRuleid());
			rtime.setRuleidtime(UUID.randomUUID().toString());
			int iruletime = ruleTimeMapper.insert(rtime);
		}
		
		if(irule > 0)
			result = true;
		
		return result;
	}

	@Override
	public List<RuleTime> getRuleTime(String ruleId) {
		// TODO Auto-generated method stub
		List<RuleTime> list = this.ruleTimeMapper.selectByRuleId(ruleId);
		return list;
	}

	@Override
	public int selectDistinct(String orgcode, String itemid,String ruleid) {
		// TODO Auto-generated method stub
		int result = this.ruleMapper.selectDistinct(orgcode, itemid,ruleid);
		return result;
	}

	@Override
	public List<RuleTime> getMaxNum(String ruleid, String reservetime) {
		// TODO Auto-generated method stub
		return this.ruleTimeMapper.getMaxNum(ruleid, reservetime);
	}

	@Override
	public List<Rule> selectDict(String orgcode){
		return ruleMapper.selectDict(orgcode);
	}
	

}
